package Procedure2;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//
public class JsonServer {
    private static final int SERVER_PORT = 8000; // 服务端端口号
    private static final String SAVE_DIR = "D:\\temp\\day03\\file"; // 文件保存目录
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
            System.out.println("Server started, listening on port " + SERVER_PORT + ".");
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                byte[] fileData = new byte[0];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byte[] temp = new byte[fileData.length + bytesRead];
                    System.arraycopy(fileData, 0, temp, 0, fileData.length);
                    System.arraycopy(buffer, 0, temp, fileData.length, bytesRead);
                    fileData = temp;
                }
                inputStream.close();
                socket.close();
                File saveDir = new File(SAVE_DIR);
                if (!saveDir.exists()) {
                    saveDir.mkdirs();
                }
                File file = new File(saveDir, "a.txt"); // 指定保存文件名称和路径，可以根据需要修改
                FileOutputStream outputStream = new FileOutputStream(file);
                outputStream.write(fileData);
                outputStream.close();
                System.out.println("File received and saved successfully.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



